/*
 * Albareth - an action roleplaying game.
 * Copyright (C) 2008 Jens Anuth
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 *   02110-1301, USA.
 * 
 * $Id: UIToolkit.java 36 2008-05-05 18:51:01Z jens464 $
*/
package albareth.frontend.slick.ui;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import org.lwjgl.LWJGLException;
import org.lwjgl.input.Cursor;
import org.newdawn.slick.Color;
import org.newdawn.slick.Font;
import org.newdawn.slick.Image;
import org.newdawn.slick.ImageBuffer;
import org.newdawn.slick.opengl.CursorLoader;

import albareth.frontend.slick.SlickResources;

import frosch.util.Log;

public class UIToolkit
{
    public static Map _colors = new HashMap();
    
    public static int getCenterStringX(String string, int width, Font font)
    {
        return (width - font.getWidth(string)) / 2;
    }

    /**
     * Simple line breaking algorithm.
     * @param text The text to break into multiple lines.
     * @param width The maximum width of a line of text, in pixels.
     * @param font The font in which the text is to be rendered.
     * @return String-Array of lines.
     */
    public static Object[] breakLines(String text, int width, Font font)
    {
        LinkedList lines = new LinkedList();
        int currentWord = 0;
    
        int stringWidth = font.getWidth(text);
        int lengthOfSpace = font.getWidth(" ");
    
        if (stringWidth > width)
        {
            String[] words = text.split(" ");
            int numWords = words.length;
            int currentLineLeft = width;
            StringBuffer lineBuffer =
                new StringBuffer((int)Math.ceil(width/stringWidth));
            while (currentWord < numWords)
            {
                int currentWordLength = font.getWidth(words[currentWord]);
                if (currentWordLength <= currentLineLeft)
                {
                    lineBuffer.append(words[currentWord]);//.append(" ");//; += words[currentword] + " ";
                    currentWord++;
                    if (currentWord < numWords) {
                        lineBuffer.append(" ");
                    }
                    currentLineLeft -= currentWordLength + lengthOfSpace;
                } else {
                    if (currentLineLeft == width)
                    {
                        String teilwort = words[currentWord];
                        lineBuffer.append(teilwort);
                        currentWord++;
                        //TODO: split word
                    }
                    lines.add(lineBuffer.toString());
                    lineBuffer = new StringBuffer((int)Math.ceil(width/stringWidth));
                    currentLineLeft = width;
                }
            }
            if (lineBuffer.length() > 0) {
                lines.add(lineBuffer.toString());
            }
        } else {
            lines.add(text);
        }
    
        return lines.toArray();
    }

    public static ImageBuffer copyImageToImageBuffer(Image image, int scale)
    {
        //System.err.println(image.toString());
        //System.err.println(image.getTexture().getTextureWidth());
        //System.err.println((int)(image.getTextureOffsetX() * image.getTexture().getWidth()));
        
         /* Sadly slick does not provide an easier way yet. */
        ImageBuffer buffer =
            new ImageBuffer(image.getWidth()*scale, image.getHeight()*scale);
    
        for (int x = 0; x < image.getWidth(); x++)
        {
            for (int y = 0; y < image.getHeight(); y++)
            {
                Color pixel = image.getColor(x, y);
                
                for (int pixX = 0; pixX < scale; pixX++) {
                    for (int pixY = 0; pixY < scale; pixY++) {
                        buffer.setRGBA(
                                x*scale + pixX,
                                (image.getHeight()-y-1)*scale +  pixY,
                                pixel.getRedByte(),
                                pixel.getGreenByte(),
                                pixel.getBlueByte(),
                                pixel.getAlphaByte()
                        );
                    }
                }
            }
        }
        return buffer;
    }
    

    public static Cursor createMouseCursorFromImage(Image image,
            int xHotspot, int yHotspot)
    {
        return createMouseCursorFromImage(image, xHotspot, yHotspot, 1);
    }
    
    
    public static Cursor createMouseCursorFromImage(Image image,
            int xHotspot, int yHotspot, int scale)
    {
        Cursor cursor = null;
        try {
            ImageBuffer buffer = copyImageToImageBuffer(image, scale);
            cursor = CursorLoader.get().getCursor(buffer, xHotspot, yHotspot);
        } catch (IOException e) {
            Log.error("Failed loading cursor: " + e);
        } catch (LWJGLException e) {
            Log.error("Failed loading cursor: " + e);
        }
        return cursor;
    }
    

    public static void drawBar(float screenX, float screenY,
                               Image imgFull, Image imgEmpty,
                               float pctFilled)
    {
        imgEmpty.draw(screenX, screenY);
        imgFull.draw(
                screenX, screenY,
                screenX + imgFull.getWidth()*pctFilled, screenY + imgFull.getHeight(),
                0, 0,
                imgFull.getWidth()*pctFilled, imgFull.getHeight()
        );
    }

    public static Color toSlickColor(String colorString)
    {
        Color color = (Color)_colors.get(colorString);
        if (color == null) {
            color = Color.decode(colorString);
            _colors.put(colorString, color);
        }
        return color;
    }

}
